/*
 * Copyright (c) 2017-present, CV4J Contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cv4j.core.filters;

import com.cv4j.core.datamodel.ImageProcessor;

import java.util.Optional;

/**
 * 聚光灯下过滤器
 *
 * @author dev
 * @date 2021/07/22
 */
public class SpotlightFilter extends BaseFilter {
    // attenuation coefficient, default is 1 means line decrease...
    private int factor;

    /**
     * 聚光灯下过滤器
     */
    public SpotlightFilter() {
        factor = 1;
    }

    /**
     * 设置的因素
     *
     * @param coefficient 系数
     */
    public void setFactor(int coefficient) {
        this.factor = coefficient;
    }

    /**
     * 做的过滤器
     *
     * @param src src
     * @return {@link Optional<ImageProcessor>}
     */
    @Override
    public Optional<ImageProcessor> doFilter(ImageProcessor src) {
        int offset = 0;
        int centerX = width / 2;
        int centerY = height / 2;
        double maxDistance = Math.sqrt(centerX * centerX + centerY * centerY);
        int tr = 0;
        int tg = 0;
        int tb = 0;
        for (int row = 0; row < height; row++) {
            offset = row * width;
            for (int col = 0; col < width; col++) {
                tr = RED[offset] & 0xff;
                tg = GREED[offset] & 0xff;
                tb = BLUE[offset] & 0xff;
                double scale = 1.0 - getDistance(centerX, centerY, col, row) / maxDistance;
                for (int i = 0; i < factor; i++) {
                    scale = scale * scale;
                }

                tr = (int) (scale * tr);
                tg = (int) (scale * tg);
                tb = (int) (scale * tb);

                RED[offset] = (byte) tr;
                GREED[offset] = (byte) tg;
                BLUE[offset] = (byte) tb;
                offset++;
            }
        }
        return Optional.ofNullable(src);
    }

    /**
     * 得到的距离
     *
     * @param centerX centerx
     * @param centerY centery
     * @param px px
     * @param py py
     * @return double
     */
    private double getDistance(int centerX, int centerY, int px, int py) {
        double xx = (centerX - px) * (centerX - px);
        double yy = (centerY - py) * (centerY - py);
        return (int) Math.sqrt(xx + yy);
    }
}
